<template>
  <view :class="['student-submit-container', currentTheme]">
    <!-- 按 positionName 分组显示学生简历 -->
    <view v-if="allStudents && allStudents.length > 0">
      <view v-for="(position, index) in allStudents" :key="index" class="position-section">
        <view class="position-title">{{ position.positionName }}</view>
        <scroll-view class="students-scroll" scroll-x>
          <view class="students-container">
            <!-- 学生列表 -->
            <view 
              v-for="(student, idx) in position.resumeRecommendList || []" 
              :key="idx" 
              class="student-card"
            >
              <image 
                class="avatar" 
                :src="student.avatar || '/static/default-avatar.png'" 
                mode="aspectFill"
              ></image>
              <view class="info-item">
                <text class="label">姓名:</text>
                <text class="value">{{ student.name || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="label">学历:</text>
                <text class="value">{{ student.education || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="label">期望工资:</text>
                <text class="value">{{ student.salary || '面议' }}</text>
              </view>
              <view class="info-item">
                <text class="label">电话:</text>
                <text class="value">{{ student.phone || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="label">邮箱:</text>
                <text class="value">{{ student.email || '未提供' }}</text>
              </view>
              <view class="info-item">
                <text class="label">毕业学校:</text>
                <text class="value">{{ student.school || '未提供' }}</text>
              </view>
              <view class="buttons">
                <button
                  class="invite-button"
                  :data-position-id="position.id"
                  :data-user-id="student.userId"
                  @click="inviteSubmit"
                >
                  邀请投递
                </button>
                <button
                  class="detail-button"
                  :data-resume-url="student.resumeUrl"
                  @click="viewDetail"
                >
                  查看简历
                </button>
              </view>
            </view>
            
            <!-- 当该职位没有学生时显示空状态 -->
            <view v-if="!position.resumeRecommendList || position.resumeRecommendList.length === 0" class="empty-container">
              <u-empty
                mode="data"
                text="暂无学生投递"
              ></u-empty>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 整体空状态 -->
    <view v-else-if="!loading" class="empty-state">
      <u-empty
        mode="data"
        text="暂无学生投递"
      ></u-empty>
    </view>

    <!-- 加载提示框 -->
    <view class="loading-mask" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{ loadingText }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getResumes } from '@/api/attachmentResume';
import { submitResume } from '@/api/job';

export default {
  data() {
    return {
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 学生数据
      allStudents: [],
      
      // 加载状态
      loading: false,
      loadingText: '正在加载简历...',
      
      // 主题数据
      currentTheme: 'theme1'
    }
  },
  computed: {
    // 按 positionName 分组学生数据
    groupedStudents() {
      return this.allStudents.reduce((groups, student) => {
        const position = student.positionName;
        if (!groups[position]) {
          groups[position] = [];
        }
        groups[position].push(student);
        return groups;
      }, {});
    }
  },
  methods: {
    // 获取学生简历数据
    async queryResume() {
      try {
        const res = await getResumes(this.currentPage, this.pageSize);
        if (res.code === 200) {
          this.allStudents = res.data.list || [];
          this.total = res.data.total || 0;
          console.log('获取到的学生数据:', this.allStudents);
        } else {
          console.error('获取简历数据失败:', res.msg);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取简历数据异常:', error);
        uni.showToast({
          title: '网络请求异常',
          icon: 'none'
        });
      }
    },
    
    // 邀请学生投递简历
    inviteSubmit(event) {
      const { positionId, userId } = event.currentTarget.dataset;
      console.log('提取到的参数:', { positionId, userId });
      if (!positionId || !userId) {
        uni.showToast({ title: '参数缺失', icon: 'none' });
        return;
      }

      this.inviteSubmitWithParams(positionId, userId, 5);
    },

    async inviteSubmitWithParams(positionId, userId, status) {
      console.log('调用 submitResume 的参数:', {
        positionId,
        userId,
        resume: '',
        status
      });

      try {
        const res = await submitResume(positionId, userId, '', status);
        console.log('submitResume 返回值:', res);
        if (res.code === 200) {
          uni.showToast({ title: '邀请成功', icon: 'success' });
          this.queryResume();
        } else {
          uni.showToast({ title: res.msg || '邀请失败', icon: 'none' });
        }
      } catch (error) {
        console.error('邀请失败:', error);
        uni.showToast({ title: '网络异常', icon: 'none' });
      }
    },
    
    viewDetail(event) {
      const { resumeUrl } = event.currentTarget.dataset;
      console.log('提取到的简历地址:', resumeUrl);

      if (!resumeUrl) {
        uni.showToast({ title: '简历地址缺失', icon: 'none' });
        return;
      }

      this.previewResume(resumeUrl);
    },
    
    // 改进的查看学生简历详情方法
    async previewResume(resumeUrl) {
      if (!resumeUrl) {
        uni.showToast({ title: '简历地址缺失', icon: 'none' });
        return;
      }

      console.log('开始预览简历:', resumeUrl);
      
      // 显示加载状态
      this.loading = true;
      this.loadingText = '正在打开简历...';
      
      try {
        // 检查文件类型
        const fileExtension = this.getFileExtension(resumeUrl);
        const supportedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
        
        if (!supportedTypes.includes(fileExtension.toLowerCase())) {
          uni.showToast({
            title: '不支持的文件格式',
            icon: 'none'
          });
          this.loading = false;
          return;
        }
        
        // 下载文件
        this.loadingText = '正在下载简历...';
        const downloadRes = await this.downloadFile(resumeUrl);
        
        if (downloadRes.statusCode === 200) {
          // 打开文档
          this.loadingText = '正在打开简历...';
          const openRes = await this.openDocument(downloadRes.tempFilePath, fileExtension);
          
          if (openRes.errMsg === 'openDocument:ok') {
            console.log('简历预览成功');
          } else {
            console.error('打开文档失败:', openRes);
            uni.showToast({
              title: '打开简历失败',
              icon: 'none'
            });
          }
        } else {
          console.error('下载文件失败:', downloadRes);
          uni.showToast({
            title: '下载简历失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('预览简历异常:', error);
        uni.showToast({
          title: '预览简历失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 获取文件扩展名
    getFileExtension(url) {
      const urlParts = url.split('?')[0]; // 移除查询参数
      const fileName = urlParts.split('/').pop();
      return fileName.split('.').pop().toLowerCase();
    },
    
    // 下载文件
    downloadFile(url) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: url,
          success: resolve,
          fail: reject
        });
      });
    },
    
    // 打开文档
    openDocument(filePath, fileType) {
      return new Promise((resolve, reject) => {
        uni.openDocument({
          filePath: filePath,
          fileType: fileType,
          success: resolve,
          fail: reject
        });
      });
    },
    
    // 分页相关方法
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.queryResume();
      }
    },
    
    nextPage() {
      if (this.currentPage * this.pageSize < this.total) {
        this.currentPage++;
        this.queryResume();
      }
    }
  },
  
  // 组件挂载时获取数据
  mounted() {
    // 加载保存的主题
    const savedTheme = uni.getStorageSync('currentTheme');
    if (savedTheme) {
      this.currentTheme = savedTheme;
    }
    this.queryResume();
  },

  onShow() {
    // 重新加载主题设置
    const savedTheme = uni.getStorageSync('currentTheme');
    if (savedTheme) {
      this.currentTheme = savedTheme;
    }
  }
}
</script>

<style scoped>
.student-submit-container {
  padding: 20rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.position-section {
  margin-bottom: 40rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
}

.position-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 20rpx;
  padding-left: 12rpx;
  border-left: 8rpx solid #3498db;
  position: relative;
}

.position-title::after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 0;
  width: 100%;
  height: 2rpx;
  background: linear-gradient(to right, #3498db, #ffffff);
}

.students-scroll {
  white-space: nowrap;
  width: 100%;
  padding: 8rpx 0;
}

.students-container {
  display: inline-block;
  min-height: 400rpx;
  padding: 20rpx 0;
}

.student-card {
  display: inline-block;
  width: 320rpx;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-right: 20rpx;
  vertical-align: top;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.student-card:hover {
  transform: translateY(-8rpx);
  box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.15);
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 300rpx;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: block;
  margin: 0 auto 15rpx;
  border: 4rpx solid #3498db;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
  font-size: 22rpx;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  background-color: #f8f9fa;
}

.info-item:last-child {
  margin-bottom: 15rpx;
}

.label {
  font-weight: bold;
  color: #3498db;
}

.value {
  color: #2c3e50;
  max-width: 160rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: right;
}

.buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 15rpx;
}

.invite-button, .detail-button {
  flex: 1;
  margin: 0 8rpx;
  border-radius: 10rpx;
  font-size: 22rpx;
  padding: 12rpx 0;
  font-weight: bold;
  transition: all 0.3s ease;
}

.invite-button {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: #fff;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(52, 152, 219, 0.4);
}

.invite-button:hover {
  background: linear-gradient(135deg, #2980b9 0%, #3498db 100%);
  transform: scale(1.05);
}

.detail-button {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  color: #3498db;
  border: 2rpx solid #3498db;
  box-shadow: 0 4rpx 12rpx rgba(52, 152, 219, 0.2);
}

.detail-button:hover {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  transform: scale(1.05);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500rpx;
}

/* 加载遮罩层样式 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  background-color: white;
  padding: 40rpx;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 20rpx;
  color: #333;
  font-size: 28rpx;
}

/* 禁用所有动画和过渡效果 */
* {
  transition: none !important;
  animation: none !important;
}

/* Theme1 样式 (蓝色主题) */
.theme1 .student-submit-container {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
}

.theme1 .position-section {
  background-color: #ffffff;
  border: 1px solid #e6f3ff;
  box-shadow: 0 6rpx 16rpx rgba(64, 158, 255, 0.1);
}

.theme1 .position-title {
  color: #1e3a8a;
  border-left-color: #409eff;
}

.theme1 .position-title::after {
  background: linear-gradient(to right, #409eff, #ffffff);
}

.theme1 .student-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8faff 100%);
  border: 1px solid #e6f3ff;
  box-shadow: 0 8rpx 16rpx rgba(64, 158, 255, 0.1);
}

.theme1 .avatar {
  border-color: #409eff;
}

.theme1 .info-item {
  background-color: #f8faff;
  border: 1px solid #e6f3ff;
}

.theme1 .label {
  color: #409eff;
}

.theme1 .value {
  color: #1e3a8a;
}

.theme1 .invite-button {
  background: linear-gradient(135deg, #409eff 0%, #2980b9 100%);
  box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.4);
}

.theme1 .detail-button {
  color: #409eff;
  border-color: #409eff;
  box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.2);
}

.theme1 .loading-spinner {
  border-top-color: #409eff;
}

.theme1 .loading-content {
  background-color: #ffffff;
  border: 1px solid #e6f3ff;
}

/* Theme2 样式 (棕色主题) */
.theme2 .student-submit-container {
  background: linear-gradient(135deg, #faf7f2 0%, #f5e6d3 100%);
}

.theme2 .position-section {
  background-color: #ffffff;
  border: 1px solid #f0e6d2;
  box-shadow: 0 6rpx 16rpx rgba(139, 69, 19, 0.1);
}

.theme2 .position-title {
  color: #8b4513;
  border-left-color: #d2691e;
}

.theme2 .position-title::after {
  background: linear-gradient(to right, #d2691e, #ffffff);
}

.theme2 .student-card {
  background: linear-gradient(135deg, #ffffff 0%, #faf7f2 100%);
  border: 1px solid #f0e6d2;
  box-shadow: 0 8rpx 16rpx rgba(139, 69, 19, 0.1);
}

.theme2 .avatar {
  border-color: #d2691e;
}

.theme2 .info-item {
  background-color: #faf7f2;
  border: 1px solid #f0e6d2;
}

.theme2 .label {
  color: #d2691e;
}

.theme2 .value {
  color: #8b4513;
}

.theme2 .invite-button {
  background: linear-gradient(135deg, #d2691e 0%, #b8860b 100%);
  box-shadow: 0 4rpx 12rpx rgba(210, 105, 30, 0.4);
}

.theme2 .detail-button {
  color: #d2691e;
  border-color: #d2691e;
  box-shadow: 0 4rpx 12rpx rgba(210, 105, 30, 0.2);
}

.theme2 .loading-spinner {
  border-top-color: #d2691e;
}

.theme2 .loading-content {
  background-color: #ffffff;
  border: 1px solid #f0e6d2;
}
</style>
